package cn.fzkj.gulimall.service.impl;

import cn.fzkj.common.to.es.SkuEsModel;
import cn.fzkj.gulimall.config.EsConfig;
import cn.fzkj.gulimall.constant.EsConstant;
import cn.fzkj.gulimall.service.MallSearchService;
import cn.fzkj.gulimall.vo.SearchParam;
import cn.fzkj.gulimall.vo.SearchResult;
import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.StringUtils;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @DESCRIPTION
 * @Author yaya
 * @DATE 2022/6/16
 */
@Service
public class MallSearchServiceImpl implements MallSearchService {

    @Autowired
    private RestHighLevelClient client;

    @Override
    public SearchResult search(SearchParam param) {

        SearchResult result = null;

        SearchRequest searchRequest = buildSearchRequest(param);

        try {
            SearchResponse response = client.search(searchRequest, EsConfig.COMMON_OPTIONS);
            result = buildSearchResult(response, param);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    private SearchResult buildSearchResult(SearchResponse response, SearchParam param) {

        SearchResult result = new SearchResult();
        // 1、返回所有商品
        SearchHits responseHits = response.getHits();
        SearchHit[] hits = responseHits.getHits();
        if (hits != null && hits.length > 0) {
            List<SkuEsModel> products = new ArrayList();
            for (SearchHit hit : hits) {
                String sourceAsString = hit.getSourceAsString();
                SkuEsModel model = JSON.parseObject(sourceAsString, SkuEsModel.class);
                if (StringUtils.isNotEmpty(param.getKeyword())){
                    HighlightField skuTitle = hit.getHighlightFields().get("sku_title");
                    String string = skuTitle.getFragments()[0].string();
                    model.setSkuTitle(string);
                }
                products.add(model);
            }
            result.setProducts(products);
        }

        // 2、当前商品涉及到的属性信息
        List<SearchResult.AttrVo> attrVos = new ArrayList<>();
        ParsedNested attr_agg = response.getAggregations().get("attr_agg");
        ParsedLongTerms attr_id_agg = attr_agg.getAggregations().get("attr_id_agg");
        for (Terms.Bucket bucket : attr_id_agg.getBuckets()) {
            SearchResult.AttrVo attrVo = new SearchResult.AttrVo();
            long attrId = bucket.getKeyAsNumber().longValue();
            attrVo.setAttrId(attrId);

            String attrName = ((ParsedStringTerms) bucket.getAggregations().get("attr_name_agg")).getBuckets().get(0).getKeyAsString();
            List<String> attrValue = ((ParsedStringTerms) bucket.getAggregations().get("attr_value_agg")).getBuckets().stream().map(item -> {
                return item.getKeyAsString();
            }).collect(Collectors.toList());
            attrVo.setAttrName(attrName);
            attrVo.setAttrValue(attrValue);

            attrVos.add(attrVo);
        }

        result.setAttrs(attrVos);

        // 3、商品涉及到的品牌信息
        List<SearchResult.BrandVo> brandVos = new ArrayList<>();
        ParsedLongTerms brand_agg = response.getAggregations().get("brand_agg");
        for (Terms.Bucket bucket : brand_agg.getBuckets()) {
            SearchResult.BrandVo brandVo = new SearchResult.BrandVo();
            brandVo.setBrandId(bucket.getKeyAsNumber().longValue());

            // 品牌名称
            ParsedStringTerms brand_name_agg = bucket.getAggregations().get("brand_name_agg");
            String brandName = brand_name_agg.getBuckets().get(0).getKeyAsString();
            brandVo.setBrandName(brandName);

            // 品牌图片
            ParsedStringTerms brand_img_agg = bucket.getAggregations().get("brand_img_agg");
            String brandImg = brand_img_agg.getBuckets().get(0).getKeyAsString();
            brandVo.setBrandImg(brandImg);

            brandVos.add(brandVo);
        }

        // 4、商品涉及到的分类信息
        List<SearchResult.CatalogVo> catalogVos = new ArrayList<>();
        ParsedLongTerms catalog_agg = response.getAggregations().get("catalog_agg");
        List<? extends Terms.Bucket> buckets = catalog_agg.getBuckets();
        for (Terms.Bucket bucket : buckets) {
            SearchResult.CatalogVo catalogVo = new SearchResult.CatalogVo();
            String catalogIdStr = bucket.getKeyAsString();
            catalogVo.setCatalogId(Long.parseLong(catalogIdStr));

            ParsedStringTerms catalog_name_agg = bucket.getAggregations().get("catalog_name_agg");
            String catalogName = catalog_name_agg.getBuckets().get(0).getKeyAsString();
            catalogVo.setCatalogName(catalogName);
            catalogVos.add(catalogVo);
        }
        result.setCatalogs(catalogVos);

        // 5、分页信息-页码
        result.setPageNum(param.getPageNum());
        // 6、分页信息-总记录数
        long total = responseHits.getTotalHits().value;
        result.setTotal(total);
        // 7、分页信息-总页码
        long totalPage = total % EsConstant.PRDUCT_PAGESIZE == 0 ? total / EsConstant.PRDUCT_PAGESIZE : total / EsConstant.PRDUCT_PAGESIZE + 1;
        result.setTotalPage((int) totalPage);

        return result;
    }

    /**
     * 构建检索请求
     * 模糊匹配， 过滤【属性、分类、品牌、价格区间、库存】，排序，分页，高亮，聚合分析
     * @param param
     * @return
     */
    private SearchRequest buildSearchRequest(SearchParam param) {
        SearchSourceBuilder sb = new SearchSourceBuilder();

        /**
         * 模糊匹配， 过滤【属性、分类、品牌、价格区间、库存】
         *       "must": [
         *         {
         *           "match": {
         *             "skuTitle": "华为"
         *           }
         *         }
         *       ],
         */
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        String keyword = param.getKeyword();
        if (StringUtils.isNotEmpty(keyword)){
            boolQuery.must(QueryBuilders.matchQuery("skuTitle", keyword));

            HighlightBuilder highlightBuilder = new HighlightBuilder();
            highlightBuilder.field("skuTitle");
            highlightBuilder.preTags("<b style='color:red'>");
            highlightBuilder.postTags("</b>");
            sb.highlighter();
        }
        /**
         *       "filter": [
         *         {
         *           "term": {
         *             "catalogId": "449"
         *           }
         *         },
         *         {
         *           "terms": {
         *             "brandId": [
         *               "12"
         *             ]
         *           }
         *         },
         *         {
         *           "nested": {
         *             "path": "attrs",
         *             "query": {
         *               "bool": {
         *                 "must": [
         *                   {
         *                     "term": {
         *                       "attrs.attrId": "12"
         *                     }
         *                   },
         *                   {
         *                     "term": {
         *                       "attrs.attrValue": {
         *                         "value": "NbDE-WFH9"
         *                       }
         *                     }
         *                   }
         *                 ]
         *               }
         *             }
         *           }
         *         },
         *         {
         *           "range": {
         *             "skuPrice": {
         *               "gte": 5000,
         *               "lte": 5900
         *             }
         *           }
         *         }
         *       ]
         */
        // 按照3级分类id查
        Long catalog3Id = param.getCatalog3Id();
        if (catalog3Id != null){
            boolQuery.filter(QueryBuilders.termQuery("catalogId", catalog3Id));
        }
        // 按照品牌id查
        List<Long> brandIds = param.getBrandId();
        if (brandIds != null && brandIds.size() > 0){
            boolQuery.filter(QueryBuilders.termsQuery("brandId", brandIds));
        }

        // 按照指定的属性查
        List<String> attrs = param.getAttrs();
        if (attrs != null && attrs.size() > 0){
            // attrs=1_5寸:8寸&attrs=2_5寸:8寸
            for (String attr : attrs) {
                BoolQueryBuilder builder = QueryBuilders.boolQuery();
                String[] s = attr.split("_");
                String attrId = s[0];  // TODO 空指针判断
                String[] attrValues = s[1].split(":");
                builder.must(QueryBuilders.termQuery("attrs.attrId", attrId));
                builder.must(QueryBuilders.termsQuery("attrs.attrValue", attrValues));
                boolQuery.filter(QueryBuilders.nestedQuery("attrs", builder, ScoreMode.None));
            }
        }

        // 按照库存查询
        boolQuery.filter(QueryBuilders.termQuery("hasStock", param.getHasStock() == 1));

        // 按照价格区间
        String skuPrice = param.getSkuPrice();
        if (StringUtils.isNotEmpty(skuPrice)){
            RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("skuPrice");
            /**
             * skuPrice=1_500/_500/500_
             */
            String[] price = skuPrice.split("_");
            // TODO 做数字校验
            if (price.length == 2){
                rangeQuery.lte(price[1]).gt(price[0]);
            }else if (price.length == 1){
                if (skuPrice.startsWith("_")){
                    rangeQuery.lt(price[1]); // 会分割空字符串
                }
                if (skuPrice.endsWith("_")){
                    rangeQuery.lte(price[0]);
                }
            }
            boolQuery.filter(rangeQuery);
        }

        /**
         * 排序，分页，高亮
         */
        String sort = param.getSort();
        if (StringUtils.isNotEmpty(sort)){
            String[] s = sort.split("_");
            SortOrder sortOrder = s[1].equalsIgnoreCase("desc") ? SortOrder.DESC : SortOrder.ASC;
            sb.sort(s[0], sortOrder);
        }

        int from = (param.getPageNum() - 1) * EsConstant.PRDUCT_PAGESIZE;

        sb.from(Math.max(from, 0));
        sb.size(EsConstant.PRDUCT_PAGESIZE);

        /**
         * 聚合
         */

        sb.query(boolQuery);
        System.out.println(sb.toString());

        SearchRequest searchRequest = new SearchRequest(new String[]{EsConstant.PRODUCT_INDEX}, sb);
        return searchRequest;
    }

    /**
        public static void main(String[] args) {
            String str = "_500";
            String[] s = str.split("_");
            System.out.println(s[0]); // ""
            System.out.println(s[1]); // 500
        }
     */
}
